package com.ych.redis.session;

import com.ych.redis.RedisUtil;
import com.ych.redis.config.RedisKeyConfig;
import com.ych.utils.TLMap;
import com.ych.utils.token.TokenSessionEntity;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.CachingSessionDAO;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;

/**
 * Created with IntelliJ IDEA.
 * Author: Usopp.tsui
 * Date: 2020/12/7
 * Time: 16:04
 * Description:
 */
public class RedisSessionDao extends CachingSessionDAO {
    @Autowired
    private RedisUtil redisTemplate;

    @Override
    protected Serializable doCreate(Session session) {
        String sessionkey = RedisKeyConfig.sessionToken(TLMap.getUserId());
        assignSessionId(session, sessionkey);
        // 2020.12.07 修改共享缓存机制
        if (StringUtils.isNotBlank(TLMap.getToken())) {
            TokenSessionEntity tokenSessionEntity = new TokenSessionEntity();
            tokenSessionEntity.setSession(session);
            tokenSessionEntity.setToken(TLMap.getToken());
            TLMap.setTlMap(sessionkey, tokenSessionEntity);
        }
        return sessionkey;
    }


    @Override
    protected Session doReadSession(Serializable sessionId) {
        String sessionkey = sessionId.toString();
        // 2020.12.07 修改共享缓存机制
        TokenSessionEntity tokenSessionEntity = (TokenSessionEntity) TLMap.getTlMap(sessionkey);
        Session session = null;
        if (null != tokenSessionEntity) {
            session = tokenSessionEntity.getSession();
        }
        if (null == session) {
            tokenSessionEntity = (TokenSessionEntity) redisTemplate.redisTemplate().opsForValue().get(sessionkey);
            if (null != tokenSessionEntity) {
                String token = tokenSessionEntity.getToken();
                if (token.equals(TLMap.getToken())) {
                    session = tokenSessionEntity.getSession();
                    TLMap.setTlMap(sessionkey, tokenSessionEntity);
                }
            }
        }
        return session;
    }

    @Override
    public Session readSession(Serializable sessionId) throws UnknownSessionException {
        Session s = doReadSession(sessionId);
        if (s == null) {
            throw new UnknownSessionException("There is no session with id [ " + sessionId + "]");
        }
        return s;
    }

    @Override
    protected void doUpdate(Session session) {
        TokenSessionEntity tokenSessionEntity = new TokenSessionEntity();
        tokenSessionEntity.setSession(session);
        tokenSessionEntity.setToken(TLMap.getToken());
        TLMap.setTlMap(session.getId().toString(), tokenSessionEntity);
    }

    @Override
    protected void doDelete(Session session) {
        TLMap.deleteTlMap(session.getId().toString());
    }

}
